/**
 * framework使用
 * Created by zeyuphoenix on 2016/4/4.
 */

/**
 * 一般提示框
 * @param message 消息内容
 * @param type 消息类型
 */
function messageBox(message, type) {

    // 设置type
    if (type == null || type != '') {
        // 根据content设置type
        if (message && message != '') {
            if (message.indexOf('Error') > 1 || message.indexOf('error') > -1
                || message.indexOf('Exception') > -1 || message.indexOf('exception') > -1) {
                type = 'error';
            } else {
                type = 'success';
            }
        }
    }
    // 过滤错误type
    if (type != 'info' && type != 'success' && type != 'danger') {
        type = 'success';
    }

    Messenger().post({
        message: message,
        type: type,
        showCloseButton: true,
        hideAfter: 8,
        hideOnNavigate: true
    });
}

/**
 *  [{'icon' : 'fa fa-user', 'title' : 'delete', 'onclick' : 'alert(1);', 'divider' : false}]
 */
function buildTableCellAction(actions) {
    // 事件
    if (actions && actions.length > 0) {
        // html
        var cell = '<div class="btn-group">' +
            '           <button class="btn btn-info dropbtn" onclick="">' +
            '           </button>' +
            '           <button class="btn btn-info dropdown-toggle" data-toggle="dropdown">' +
            '               <span class="caret"></span>' +
            '           </button>' +
            '           <ul class="dropdown-menu">' +
            '           </ul>' +
            '       </div>';
        var $cell = $(cell);
        $.each(actions, function (i, value) {
            // btn
            if (i == 0) {
                $cell.find('.dropbtn').append('<i class="' + value['icon'] + '"></i> ' + value['title'])
                    .attr('onclick', value['onclick']);
            } else {
                // drop menu
                if (value['divider'] && value['divider'] == true) {
                    $cell.find('.dropdown-menu').append('<li class="divider"></li>');
                } else {
                    $cell.find('.dropdown-menu').append(
                        '<li>' +
                        '   <a href="javascript:" onclick="' + value['onclick'] + '">' +
                        '       <i class="' + value['icon'] + '"></i> ' + value['title'] +
                        '   </a>' +
                        '</li>');
                }
            }
        });
        return $cell.get(0);
    }
    return '';
}

// 页面$.ajax的结果统一处理
// 因为子页面的载入也是Ajax方式,所以如果全局$.ajax上增加处理可能会有问题
function ajaxCoomand(options) {
    //默认配置
    var setting = {
        //A string containing the URL to which the request is sent.
        url: '',
        /**
         * ajax type: get or post
         *
         * default is POST
         */
        type: 'POST',

        // use the traditional style of param serialization.
        traditional: true,

        // Data to be sent to the server. It is converted to a query string
        data: '',

        /**
         * The type of data that you're expecting back from the server.
         *  "xml"、"html"、"script"、"json"、"jsonp"、"text"
         *
         *  default is json
         */
        dataType: 'json',

        // By default, all requests are sent asynchronously (i.e. this is set to true by default)
        async: true,

        //回调函数
        callback: '',

        // 存在遮罩,默认true
        hasLoading: true,

        /**
         * 默认增加遮罩,可以根据
         */
        beforeSend: function () {
            if (setting.callback == true) {
                layer.load(0, {shade: 0.4});
            }
        },

        /**
         * A function to be called if the request succeeds.
         * The function gets passed three arguments: The data returned from the server
         */
        success: function (data) {
            if (data && data.status == 'success') {
                if (setting.callback != "") {
                    setting.callback(data);
                }
                messageBox(data.message, "success");
            } else {
                messageBox(data.message, "error");
            }
        },

        /**
         * A function to be called if the request fails.
         */
        error: function (jqXHR) {
            switch (jqXHR.status) {
                case(401):
                    messageBox("未登录", "error");
                    break;
                case(403):
                    messageBox("无权限执行此操作", "error");
                    break;
                case(404):
                    messageBox("操作不存在", "error");
                    break;
                case(408):
                    messageBox("请求超时", "error");
                    break;
                case(500):
                    messageBox("服务器系统内部错误", "error");
                    break;
                default:
                    messageBox("未知错误", "error");
            }
        },

        /* error or success will running,*/
        complete: function () {
            // close tip layer
            layer.closeAll('loading');
        }
    };

    // 覆盖默认配置
    if (options) {
        $.extend(setting, options);
    }

    $.ajax(setting);
}

// 获取URL地址参数
function getQueryString(name, url) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    if (!url || url == "") {
        url = window.location.search;
    } else {
        url = url.substring(url.indexOf("?"));
    }
    r = url.substr(1).match(reg)
    if (r != null) return unescape(r[2]);
    return null;
}
// 为password文本框增加显示效果
function password_feedback($form, callback) {
    // 密码加上显示
    $form.find('input[type="password"]').each(function (i, input) {
        var $input = $(input);

        $input.closest('div').addClass("has-feedback");
        $('<span>').addClass(
            "form-control-feedback fa fa-eye password-icon"
        ).insertAfter($input).click(function () {
            var $icon = $(this);

            if ($input.attr('type') === 'password') {
                $icon.removeClass('fa-eye');
                $icon.addClass('fa-eye-slash');
                $input = change_input_type($input, 'text');
            } else {
                $icon.removeClass('fa-eye-slash');
                $icon.addClass('fa-eye');
                $input = change_input_type($input, 'password');
            }
        });
    });
    // 更改类型
    function change_input_type($input, type) {
        /*
         * In a perfect world, this function would just do:
         *   $input.attr('type', type);
         * however, Microsoft Internet Explorer exists and we have to support it.
         */
        var $new_input = $input.clone();

        $new_input.attr('type', type);
        $input.replaceWith($new_input);
        if (callback) {
            callback();
        }
        return $new_input;
    }
}
// 内内嵌页面设置固定高度
function tableHeightSize() {

    if ($('body').hasClass('menu-on-top')) {
        var menuHeight = 68;
        // nav height

        var tableHeight = ($(window).height() - 224) - menuHeight;
        if (tableHeight < (320 - menuHeight)) {
            $('.table-wrap').css('height', (320 - menuHeight) + 'px');
        } else {
            $('.table-wrap').css('height', tableHeight + 'px');
        }

    } else {
        var tableHeight = $(window).height() - 224;
        if (tableHeight < 320) {
            $('.table-wrap').css('height', 320 + 'px');
        } else {
            $('.table-wrap').css('height', tableHeight + 'px');
        }

    }
}
/**
 * 转换流量、流量速率、存储、内存大小等以1024为换算的值
 */
function flowTransform(val, offset) {

    var fix = 2;
    if (offset != null && fix != 'undefined') {
        fix = offset;
    }

    if (val == 0) {
        return val;
    }
    if (val < 1024) {
        return val + " B";
    } else if (val < 1048576) {
        return (val / 1024).toFixed(fix) + " KB";
    } else if (val < 1073741824) {
        return (val / 1048576).toFixed(fix) + " MB";
    } else {
        return (val / 1073741824).toFixed(fix) + " GB";
    }
}
/**
 * 转换报文数、统计数、计算数等以1000为换算的值
 */
function packetTransform(val, offset) {

    var fix = 2;
    if (offset != null && fix != 'undefined') {
        fix = offset;
    }

    if (val == 0) {
        return val;
    }
    if (val < 1000) {
        return val + " ";
    } else if (val < 1000000) {
        return (val / 1000).toFixed(fix) + " K";
    } else if (val < 1000000000) {
        return (val / 1000000).toFixed(fix) + " M";
    } else {
        return (val / 1000000000).toFixed(fix) + " G";
    }
}